//
//  HDHomeController.swift
//  HDSwfitWeibo
//
//  Created by wty on 16/4/7.
//  Copyright © 2016年 wty. All rights reserved.
//

import UIKit
import SVProgressHUD
import MJRefresh
let ReuseIdentifier = "ReuseIdentifier"
class HDHomeController: HDBaseViewController {

    //模型数组
    var stastus:[HDStatus]?{
        didSet {
            self.tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //判断用户是否登录  如果未登录就不做任何操作
        if !HDUserAccoutViewModel.userAccoutShare.userLogin{
            return
        }
//        //MARK -下拉刷新相关
//        //添加刷新控件
        tableView.addSubview(pullDownRefreshControl)
        //刷新闭包回调  刷新的时候调用的方法
        pullDownRefreshControl.pullToRefreshHandler = {
            //加载数据
             self.loadNewData()
        }
        //一进来就刷新
        pullDownRefreshControl.beginRefreshing()

        //设置导航条内容
        setNavigationBar()
        //设置tableView属性
        setupTableView()
        //创建刷新控件
        refresh()
       //图层异步绘制
        
        
    }
     //MARK -网络请求获取数据
    //创建刷新控件
    private func refresh() {
        //下拉刷新控件
//        tableView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: Selector("xxx"))
//        tableView.mj_header.beginRefreshing()
        //上拉刷新控件
        tableView.mj_footer =  MJRefreshAutoFooter.init(refreshingTarget: self, refreshingAction: Selector("loadMoreDate"))
    }


    //加载新数据   TODO
    private func loadNewData() {
        //获取id最大的微博  当第一次进入的时候(第一次手动拖拽)  since_id = 0  就是会默认加载最新的20条数据
        let since_id  = stastus?.first?.id ?? 0
         HDStatusViewModel.statusShare.loadStatus(since_id, max_id: 0) { (statuses, error) -> () in
            HDPrint(error)
            //关闭刷新控件
            self.pullDownRefreshControl.endRefreshing()
//           self.tableView.mj_header.endRefreshing()

            //错误提示
            if error != nil{
                SVProgressHUD.showErrorWithStatus("网络不给力")
                return
            }
      
            //获取新的微博数量
            let count = statuses?.count ?? 0
            //下拉刷新数量提示
            if since_id != 0 {
                //表示用户手动拖拽显示
                self.showTipLabel(count)
            }
            //如果新增加的微博为0  不做任何操作  不然下面强制拆包会崩
            if count == 0 {
                if since_id == 0  {
                SVProgressHUD.showInfoWithStatus("没有微博")
                }
                return
            }
            
            
            if since_id == 0  {
                  self.stastus = statuses
//                //MARK -上拉刷新相关
//                self.tableView.addInfiniteScrollingWithActionHandler { () -> Void in
//                    self.loadMoreDate()
                }else{
                 self.stastus = statuses! + self.stastus!
                 }
        }
    }

    //上拉刷新获取数据
    func  loadMoreDate(){
        //获取max_id
        let max_id = self.stastus?.last?.id ?? 0
        //如果没有数据 就不要曹组
        if max_id == 0{
            return
        }
        //加载跟多数据
        HDStatusViewModel.statusShare.loadStatus(0, max_id: max_id) { (statuses, error) -> () in
            //结束刷新
            if error != nil{
                SVProgressHUD.showErrorWithStatus("加载出错")
                return
            }
            //防止下面强制解包 崩
            let count = statuses?.count ?? 0
            if count == 0 {
                return
            }
            self.stastus = self.stastus!+statuses!
            
        }
        
    }
    //显示下拉刷新的提示
    private func showTipLabel(count:Int){
        let tipLabelHeight:CGFloat = 44
        let y = -(20+tipLabelHeight)
        self.showTipLabel.frame = CGRect(x: 0, y: y, width: ScreenW, height: tipLabelHeight)
       self.showTipLabel.text = count == 0 ? "没有新的微博数" : "下拉刷新了\(count)条数据"
       //动画叠加问题
        if let key = showTipLabel.layer.animationKeys() {
            //来知道这里叠加动画 return 就好
            HDPrint(key)
            return
        }
        //动画改变frame
        UIView.animateWithDuration(animationCurtation, animations: { () -> Void in
            self.showTipLabel.frame.origin.y =  tipLabelHeight
            }) { (_) -> Void in
                //延时动画
                UIView.animateWithDuration(animationCurtation, delay: 1, options: [], animations: { () -> Void in
                    //UIView动画反过来执行 就是放回之前状态
                    UIView.setAnimationRepeatAutoreverses(true)
                    }, completion: { (_) -> Void in
                       self.showTipLabel.removeFromSuperview()
                })

        }
    }

    //MARK -设置tableView属性
    private func  setupTableView(){
        //注册cell
        tableView.registerClass(HDStatusCell.self, forCellReuseIdentifier:ReuseIdentifier )
        //设置自动布局的行高
//        tableView.estimatedRowHeight = 200
//        tableView.rowHeight = UITableViewAutomaticDimension
        //取消分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    }
    
    
    //MARK -设置导航条内容
    private func setNavigationBar() {
        //左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_friendattention", highlightedIamgeName: "navigationbar_friendattention-1", target: self, action: Selector("leftBarBtnClick"))
        //右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_pop", highlightedIamgeName: "navigationbar_pop_highlighted", target: self, action: Selector("rightBarBtnClick"))
        //设置中间titleView  titleView 自定义
        //可选值 绑定简易写法
        let name = HDUserAccoutViewModel.userAccoutShare.userAccount?.screen_name ?? "没有名字"
        let titieBtn = HDTitleBtn(title: name)
        titieBtn.addTarget(self, action: Selector("titieBtnClick:"), forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView =  titieBtn


    }
    //   按钮监听方法
    @objc private  func leftBarBtnClick() {
        
    }
    @objc private func rightBarBtnClick() {
        
    }
    @objc private func titieBtnClick(titleBtn:HDTitleBtn) {
        titleBtn.selected = !titleBtn.selected
        //如果没有背景图片  根据按钮状态来选择动画
        UIView.animateWithDuration(animationCurtation) { () -> Void in
          titleBtn.imageView!.transform =    titleBtn.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.001)) :  CGAffineTransformIdentity
        }
    }
    //MARK  -懒加载刷新控件
    private lazy var pullDownRefreshControl :HDPullDownRefreshControl = HDPullDownRefreshControl()
    private lazy var showTipLabel : UILabel = {
        let  label = UILabel(color: UIColor.whiteColor(), fontsize: 14)
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = NSTextAlignment.Center
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
       return label
    }()
}
//MARK: - Table view 代理方法
extension HDHomeController {


    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableView.mj_footer.hidden = (self.stastus?.count == 0)
        return self.stastus?.count ?? 0

    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifier,forIndexPath: indexPath)as! HDStatusCell

        cell.status = self.stastus?[indexPath.row]
        return cell
    }
    //取消点击cell的高亮状态
    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }
    //自己计算行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        //获取模型
        let  staues = self.stastus![indexPath.row]
        //判断模型中是否缓存 如果缓存了就在缓存中拿
        if  staues.cellHeight != nil {
            return staues.cellHeight!
        }
        //创建cell  不用于展示为了赋值cell内容 来展示高度
        let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifier) as! HDStatusCell
        cell.status = staues
        let cellHeight = cell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
        //保存行高
        staues.cellHeight = cellHeight
        return cellHeight
        
    }
  
}
